#include<iostream>
#include<unistd.h>
#include <sys/types.h>         
#include <sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>

#include"Epoll.hpp"
#include"Connection.hpp"
#include"Reactor.hpp"
#include"HandleFunc.hpp"

int main(int argn,char* argv[])
{
    if(2!=argn)
    {
        printf("Usage error:%s\nUsage: %s port\n",argv[0],argv[0]);
        exit(-1);
    }
    Reactor reactor(htons(std::stoi(argv[1])),AcceptClientLink);
    reactor.Start();
        //创建监听套接字
        int _listenSocket=socket(AF_INET,SOCK_STREAM,0);
        if(_listenSocket<0)
        {
            Log(FATAL,"create listening socket error\n");
            return 0;
        }
        Log(DEBUG,"create listening socket %d successfully\n",_listenSocket);
        //设置地址复用
        int opt=1;
        if(setsockopt(_listenSocket,SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))<0)
        {
            Log(ERROR,"set address reuse error\n");
        }
        Log(DEBUG,"set address reuse succeffully\n");
        //绑定端口号
        struct sockaddr_in saddr;
        bzero(&saddr,sizeof(saddr));
        saddr.sin_family=AF_INET;
        saddr.sin_port=htons(std::stoi(argv[1]));
        saddr.sin_addr.s_addr=INADDR_ANY;
        
        if(bind(_listenSocket,(struct sockaddr*)(&saddr),sizeof(saddr))<0)
        {
            Log(FATAL,"bind error\n");
        }
        Log(DEBUG,"bind succeffully\n");
        //开启监听
        if(listen(_listenSocket,5)<0)
        {
            Log(FATAL,"listen error\n");
        }
        Log(DEBUG,"listen succeffully\n");

        int _fd=epoll_create(defaultEpollSize);
        if(_fd<0)
        {
            Log(FATAL,"epoll create error\n");
            return 0;
        }
        Log(DEBUG,"epoll create successfully\n");

        struct epoll_event ee;
        bzero(&ee,sizeof(ee));
        ee.events=EPOLLIN;
        ee.data.fd=_listenSocket;
        if(epoll_ctl(_fd,EPOLL_CTL_ADD,_listenSocket,&ee)<0)
        {
            Log(ERROR,"epoll add error\n");
            return false;
        }
        Log(DEBUG,"epoll add %d successfully\n",_listenSocket);
        struct epoll_event _readyEvents[10];
        while(true)
        {
            struct sockaddr_in client;
            bzero(&client,sizeof(client));
            socklen_t len=sizeof(client);
            int n=epoll_wait(_fd,_readyEvents,10,-1);
            if(n>0)
            {
                Log(DEBUG,"accept successfully\n");
                int sockfd=accept(_listenSocket,(struct sockaddr*)&client,&len);
            }
        }
    return 0;
}